//文件上传
import React, { Component } from 'react';
import {
	Radio,
	Form,
	Input,
	Modal,
	Button,
	Upload,
	message,
	Space,
	Table,
	Select,
	Alert,
	// Progress
} from 'antd';
import { typeMap } from '../../typeMap';
import { FormInstance } from 'antd/lib/form';

import { PaperClipOutlined } from '@ant-design/icons';


// import { dataSource, stringColumns } from '../mock';

import { delFile, createFileSource, appendFileSource, resetFileResource } from 'src/services/DataManage/index';

import { createFileSourceInput } from 'src/services/DataManage/type';

import { baseUplaodURl } from 'src/services';


interface AddUploadFileModalProps {
	uploadModalVisible:boolean,
	closeModal: ( value: boolean ) => void;
	fileEdit:boolean
	data:any
	getList:any
}

interface AddUploadFileModalState {
	columns:any
	dataSource:any
	dataColumns:any
	uploadType:number
	fileId:string
	// percent:number
	fileList:any
	click:boolean
}


class AddUploadFileModal extends Component<AddUploadFileModalProps,AddUploadFileModalState> {

	formRef = React.createRef<FormInstance>()

	constructor( props:AddUploadFileModalProps ) {
		super( props );
		this.state = {
			columns: [],
			dataSource: [],
			dataColumns: {},
			uploadType: 1, //1 追加上传 2为重新上传
			fileId: '',
			// percent: 0,
			fileList: [],
			click: false,
		};
	}

	componentDidUpdate( prevProps: Readonly<AddUploadFileModalProps>, prevState: Readonly<AddUploadFileModalState>, snapshot?: any ): void {
		if( this.props.fileEdit ) {
			this.formRef.current.setFieldsValue( {
				name: this.props.data.name,
				comments: this.props.data.comments,
			} );
		}
	}


	//处理取消关闭操作
	handlCancel = () => {
		this.props.closeModal( false );
		//初始化form
		this.formRef.current.resetFields();
		if( this.state.fileId ) {
			//关闭时删除文件
			this.delUploadFile();
		}
		//重置上传类型
		this.setState( { columns: [],
			dataSource: [],
			dataColumns: {},
			click: false,
			fileList: [],
			uploadType: 1, //1 追加上传 2为重新上传
			fileId: '', } );
	}
	
	//取消时删除已上传文件
	delUploadFile = async () => {
		delFile( {
			'data': this.state.fileId,
		} );
		// console.log( info );
	}

	//上传前文件验证
	beforeUpload = ( file,fileList ) => {
		//文件类型列表
		console.log( file );
		const fileTypes = [
			'xlsx',//xlsx
			'xls',//xls
			'csv'
		];

		//前端文件类型校验
		const isExcel = fileTypes.some( v => file.name.indexOf( v ) > -1 );
		if ( !isExcel ) {
			message.error( '文件格式不正确，请修改后重新上传！', 0.8 );
			return Promise.reject();
		}

		//前端文件大小限制20m
		const isLt20M = file.size / 1024 / 1024 < 20;
		if ( !isLt20M ) {
			message.error( `${file.name  }文件大小超出限制，请修改后重新上传`, 0.8 );
			return Promise.reject();
		}

		if( this.state.fileList.length===0 ) {
			this.setState( { fileList: [ ...fileList ] } );
		}else{
			message.error( '只能上传一个文件' );
			return false;
		}
		return isExcel && isLt20M;

	};

	//处理form提交
	handleModalOk = () => {
		if( !this.state.click ) {
			//给提交事件加锁
			this.setState( { click: true },() => {
				// console.log( this.state.click );
				this.formRef.current.validateFields().then( value => {
					if( this.props.fileEdit ) {
						//追加
						if( this.state.uploadType === 1 ) {
							// console.log( '追加' );
							// console.log( this.props.data );
							let data = { columns: this.state.dataColumns,
								fileId: this.state.fileId,
								'dbId': this.props.data.id, };
							this.handeleAppendSource( { 'data': data }  );
						}else {
							//	重新
							// console.log( '重新' );
							let data = { columns: this.state.dataColumns,
								fileId: this.state.fileId,
								'dbId': this.props.data.id, };
							this.handleResetResource( { 'data': data } );
						}
					}else {
						// console.log( '新建' );
						let data = { ...value,
							...this.props.data,
							columns: this.state.dataColumns,
							fileId: this.state.fileId, };
						delete data.file;
						this.handelCreate( { 'data': data } );
					}
				} ).catch( info =>  {message.warning( '请完善信息' );this.setState( { click: false } );} );
			} );
		}
	}

	//重新上传成功
	handleResetResource = ( data:createFileSourceInput ) => {
		resetFileResource( data ).then( result => {
			if ( result.data && result.data.success ) {
				message.success( '重新上传成功' );
				this.setState( { fileId: '' } );
				this.handlCancel();
				this.props.getList();
			}else {
				this.setState( { click: false } );
			}
		} );
		
	}

	//追加文件数据源
	handeleAppendSource = ( data:createFileSourceInput ) => {
		appendFileSource( data ).then( result => {
			if ( result.data && result.data.success ) {
				message.success( '追加上传成功' );
				this.setState( { fileId: '' } );
				this.handlCancel();
				this.props.getList();
			}else {
				this.setState( { click: false } );
			}
		} );
	}

	
	//创建文件数据源:
	handelCreate = ( data:createFileSourceInput ) => {
		createFileSource( data ).then( result => {
			if ( result.data && result.data.success ) {
				message.success( '创建成功' );
				this.setState( { fileId: '' } );
				this.handlCancel();
				this.props.getList();
			}else {
				this.setState( { click: false } );
			}
		} );
		
	}
	
	//文件上传
	normFile = e => {
		console.log( 'Upload event:', e );
		if ( Array.isArray( e ) ) {
			return e;
		}
		return e && e.fileList;
	};

	//移除文件操作
	handleFileRemove = file => {
		this.setState( { dataColumns: {},fileId: '',dataSource: [],columns: [],fileList: [] } );
	}
	
	//数据预览表头处理
	handleTableHeader = s => {
		return Object.keys( s ).map( name => {
			let t = s[name];
			// let data = this.state.dataColumns;
			// data[name] = t;
			// this.setState( {
			// 	dataColumns: data
			// } );
			return {
				title: this.downSelect( t,name ),
				dataIndex: name,
				key: name,
			};
		} );
	}
	
	
	//根据默认值制作选择
	downSelect = ( v,t ) => {
		return(
			<>
				<Select defaultValue={v}
					onChange={v => {
						let data = this.state.dataColumns;
						data[t] = v;
						this.setState( {
							dataColumns: data
						} );
					}}>
					{
						typeMap.map( item =>
							<Select.Option key={item.value} value={item.value}>{item.name}</Select.Option> )
					}
				</Select>
				<div>{t}</div>
			</>
		);
	}

	//修改上传类型
	uploadTypeChange = e => {
		this.setState( {
			uploadType: e.target.value
		} );
	}
	
	//文件上传
	handleFileChange = ( info ) => {
		// let { event } = info;
		// if ( event ) { // 一定要加判断，不然会报错
		// 	let percent = Math.floor( ( event.loaded / event.total ) * 100 );
		//
		// 	this.setState( { percent: percent } );
		// 	console.log( percent ); // percent就是进度条的数值
		// }

		if ( info.file.status === 'uploading' ) {
			console.log( '上传中。' );
		}
		if ( info.file.status === 'done' ) {
			const { data } = info.file.response;
			if ( data ) {
				let columns = this.handleTableHeader( data.columns );
				this.setState(
					{ 'fileId': data.fileId,
						'dataColumns': data.columns,
						'dataSource': data.lines.map( ( item,index ) => ( { ...item,key: index } ) ),
						columns },
				);
				console.log( '上传成功。' );
				// console.log( this.state.fileList )
			}else {
				message.warning( info.file.response.message );
			}
		} else if ( info.file.status === 'error' ) {
			console.log( '上传失败。' );
		}

		this.setState( { fileList: [ ...info.fileList ] } );
	}

	componentDidMount(): void {
		const formDisable = this.props.fileEdit &&  this.props.data.effect === 'ENABLE';
		if( formDisable ) {
			this.setState( { click: formDisable } );
		}
	}
	
	// shouldComponentUpdate( nextProps: Readonly<AddUploadFileModalProps>, nextState: Readonly<AddUploadFileModalState>, nextContext: any ): boolean {
	// 	if( this.state.click !== nextState.click ) {
	// 		return  true;
	// 	}
	// }

	render() {
		const layout = {
			labelCol: { span: 5 },
			wrapperCol: { span: 18 },
		};
		return (
    		<Modal
				destroyOnClose
				title={this.props.fileEdit?'更新上传':'上传Excel/CSV'}
				cancelText={'取消'}
				okText={'添加'}
				okButtonProps={ { disabled: this.state.click } }
				onCancel={this.handlCancel}
				onOk={this.handleModalOk}
				width={1400}
				forceRender={true}
				visible={ this.props.uploadModalVisible }>
				<Form
					{...layout}
					ref={this.formRef}
					name="basic"
				>
					{ this.state.click ? ( <Alert message="数据正在上传，请稍等。" type="warning" style={ { marginBottom: '24px' } } /> ) : null }
					<Form.Item
						label="数据源名称"
						name="name"
						rules={[ { required: true, message: '请输入数据源名称！' } ]}
					>
						<Input disabled={this.state.click} />
					</Form.Item>

					<Form.Item
						label="描述"
						name="comments"
					>
						<Input disabled={this.state.click} />
					</Form.Item>
					{
						this.props.fileEdit
							? <Form.Item>
								<Radio.Group onChange={this.uploadTypeChange} value={this.state.uploadType} disabled={this.state.click}>
									<Radio value={1}>追加上传</Radio>
									<Radio value={2}>重新上传</Radio>
								</Radio.Group>
							</Form.Item>
							:null
					}
					<Form.Item
						name="file"
						wrapperCol={{ span: 23 }}>
						{/*文件上传*/}
						<Upload
							action={`${baseUplaodURl }/bdhapi/uploadfilebi/data`}
							onChange={this.handleFileChange}
							beforeUpload={this.beforeUpload}
							onRemove={this.handleFileRemove}
							disabled={this.state.click}
							withCredentials
							// progress={{type:'line'}}
							fileList={this.state.fileList}
							accept=".xls, .xlsx,.csv">
							<Space>
								<Button icon={<PaperClipOutlined />} disabled={this.state.click} >添加文件</Button>
								<span>(只能上传xlsx/xls/csv文件，且不超过20m)</span>
							</Space>
						</Upload>
					</Form.Item>
				</Form>
				<Table dataSource={this.state.dataSource}
					   columns={this.state.columns}
					   size="small"
					   scroll={{ x: true }}
					   pagination={false}/>
    		</Modal>
    	);
	}
};

export default AddUploadFileModal;